package com.eascs.archive.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.dao.O2oZxDao;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveDao;
import com.eascs.archive.entity.ArchiveLinkEntity;
import com.eascs.archive.entity.CreditArchiveRecordEntity;
import com.eascs.archive.entity.FieldEntity;
import com.eascs.archive.service.ArchiveService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class ArchiveServiceImpl implements ArchiveService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Value("${o2o.admin.creditAchive}")
	private String creditAchive;
	@Autowired
	private ArchiveDao archiveDao;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	WorkFlowService workFlowService;
	@Autowired
	O2oZxDao o2oZxDao;

	@Override
	public List<FieldEntity> getFieldListByType(String bankTypeId, String formTypeId) {
		try {
			List<FieldEntity> fields = new ArrayList<>();
			List<ArchiveLinkEntity> archiveLinkList = archiveDao.getArchiveLinkList(bankTypeId, formTypeId);
			for (ArchiveLinkEntity archiveLink : archiveLinkList) {
				PubDditem pubDditem = archiveDao.getFieldById(archiveLink.getFieldId());
				FieldEntity field = new FieldEntity(archiveLink.getFieldId(), pubDditem.getItemCode(),
						pubDditem.getItemName(), archiveLink.getFieldRequired(), archiveLink.getFieldMin(),
						archiveLink.getFieldMax());
				fields.add(field);
			}
			return fields;
		} catch (Exception e) {
			logger.info("档案归档，获取动态表单字段出错 bankTypeId:[{}],formTypeId[{}] errorMsg:[{}]", bankTypeId, formTypeId,
					e.getMessage());
		}
		return null;
	}

	@Override
	public List<FieldEntity> getFieldListAll() {
		try {
			List<FieldEntity> fields = new ArrayList<>();
			List<PubDditem> pubDditem = archiveDao.findAllFiles();
			for (PubDditem item : pubDditem) {
				FieldEntity field = new FieldEntity(item.getItemNo(), item.getItemCode(), item.getItemName(), "true", 1,
						10);
				fields.add(field);
			}
			return fields;
		} catch (Exception e) {
			logger.info("档案归档，获取动态表单字段出错 errorMsg:[{}]", e);
		}
		return null;
	}

	@Override
	public void handStartUp(String id) {
		WFRequestParam param = new WFRequestParam();
		CreditArchiveRecordEntity creditArchiveRecordEntity = archiveDao.getById(CreditArchiveRecordEntity.class, id);
		// O2oLoanapplyEntity loan =
		// o2oLoanapplyService.findById(creditArchiveRecordEntity.getLoanapplyNo());
		O2oZxEntity zxEntity = o2oZxDao.getById(O2oZxEntity.class, creditArchiveRecordEntity.getLoanapplyNo());
		O2oLoanUserEntityZx zxUserEntity = o2oZxDao.getLoanUserZx(zxEntity.getId());
		param.setReferId(creditArchiveRecordEntity.getId());
		param.setReferCode(creditArchiveRecordEntity.getBillCode());
		param.setReferUrl(creditAchive);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("CREDIT_ARCHIVE");
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(zxEntity.getLtd());

		String customerTypeDes = null;
		if (StringUtils.equals(zxEntity.getZxType(), "ZX_JKR")) {
			customerTypeDes = "借款人";
		} else if (StringUtils.equals(zxEntity.getZxType(), "ZX_PO")) {
			customerTypeDes = "配偶";
		} else if (StringUtils.equals(zxEntity.getZxType(), "ZX_DBR")) {
			customerTypeDes = "担保人";
		}

		// 3.生成摘要
		// O2oLoanUserEntity loanUser =
		// o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),
		// loan.getLoanId());
		// Integer customerType = creditArchiveRecordEntity.getCustomerType();
		// String type = customerType==0?"借款人":customerType==1?"配偶":"担保人";
		String appliedDes = "征信查询人：" + zxUserEntity.getUserFullName() + "（" + customerTypeDes + "）";
		param.setAppliedDes(appliedDes.toString());
		logger.info("启动征信归档，参数有id：【{}】，编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", zxEntity.getId(),
				zxEntity.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, "CREDIT_ARCHIVE", zxEntity.getLtd());

		// 4.启动工作流
		com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess()) {
			creditArchiveRecordEntity.setIsStart("Y");
			creditArchiveRecordEntity.setStatus(StatusContexts.ZXGD_RUN);
			creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_RUN);
		} else {
			creditArchiveRecordEntity.setIsStart("N");
			creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_NEW);
			logger.error("启动征信归档失败，单号为：【{}】，错误信息{}", zxEntity.getBillCode(), modelResult.getErrMsg());
			throw new RuntimeException(modelResult.getErrMsg());
		}
		archiveDao.updateById(creditArchiveRecordEntity);
	}

}
